#!/bin/bash

# 环境检查脚本
# 用于验证CentOS 7环境中部署所需的依赖是否已正确安装

echo "检查酒店管理系统部署环境..."

# 检查操作系统
echo "检查操作系统版本..."
if [[ -f /etc/redhat-release ]]; then
    OS_VERSION=$(cat /etc/redhat-release)
    echo "  操作系统: $OS_VERSION"
    if [[ $OS_VERSION == *"CentOS Linux release 7."* ]]; then
        echo "  ✓ 操作系统版本兼容"
    else
        echo "  ! 警告: 可能不完全兼容的CentOS版本"
    fi
else
    echo "  ! 未检测到CentOS系统"
fi

# 检查Docker
echo "检查Docker..."
if command -v docker &> /dev/null; then
    DOCKER_VERSION=$(docker --version)
    echo "  Docker版本: $DOCKER_VERSION"
    echo "  ✓ Docker已安装"
    
    # 检查Docker服务状态
    if systemctl is-active --quiet docker; then
        echo "  ✓ Docker服务正在运行"
    else
        echo "  ✗ Docker服务未运行，请执行: sudo systemctl start docker"
    fi
else
    echo "  ✗ Docker未安装，请先安装Docker"
fi

# 检查Docker Compose
echo "检查Docker Compose..."
if command -v docker-compose &> /dev/null; then
    DOCKER_COMPOSE_VERSION=$(docker-compose --version)
    echo "  Docker Compose版本: $DOCKER_COMPOSE_VERSION"
    echo "  ✓ Docker Compose已安装"
else
    echo "  ✗ Docker Compose未安装，请先安装Docker Compose"
fi

# 检查Git
echo "检查Git..."
if command -v git &> /dev/null; then
    GIT_VERSION=$(git --version)
    echo "  Git版本: $GIT_VERSION"
    echo "  ✓ Git已安装"
else
    echo "  ✗ Git未安装，请先安装Git"
fi

# 检查端口占用
echo "检查端口占用情况..."
PORTS=(80 3306 5000)
for PORT in "${PORTS[@]}"; do
    if netstat -tlnp | grep -q ":$PORT "; then
        PROCESS=$(netstat -tlnp | grep ":$PORT " | awk '{print $7}')
        echo "  ! 端口 $PORT 已被占用 ($PROCESS)"
    else
        echo "  ✓ 端口 $PORT 未被占用"
    fi
done

# 检查当前目录权限
echo "检查目录权限..."
if [ -w . ]; then
    echo "  ✓ 当前目录具有写权限"
else
    echo "  ✗ 当前目录没有写权限"
fi

# 检查必要文件
echo "检查必要文件..."
REQUIRED_FILES=("docker-compose.yml" "Dockerfile" "app.py" "requirements.txt")
for FILE in "${REQUIRED_FILES[@]}"; do
    if [ -f "$FILE" ]; then
        echo "  ✓ $FILE 存在"
    else
        echo "  ✗ $FILE 不存在"
    fi
done

echo ""
echo "环境检查完成。"
echo "请确保所有标记为✗的项目都已正确安装和配置后再进行部署。"